package grimbo.goodwinfooty.server.mvc;

import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 * Handles the items in a ServletFileUpload's FileItemIterator by calling a
 * callback.
 */
public class UploadHelper {
	private static final String CNAME = UploadHelper.class.getName();
	private static final Logger log = Logger.getLogger(CNAME);

	/**
	 * Returns true if request has file param.
	 * 
	 * @param req
	 * @return
	 */
	public boolean isMultipartRequest(HttpServletRequest req) {
		return ServletFileUpload.isMultipartContent(req);
	}

	/**
	 * @param req
	 * @param handler
	 * @throws FileUploadException
	 * @throws IOException
	 */
	public void handleRequest(HttpServletRequest req,
			FileItemStreamHandler handler) throws FileUploadException,
			IOException {
		final String MNAME = "handleRequest(HttpServletRequest, FileItemStreamHandler)";
		final boolean DEBUG = log.isLoggable(Level.FINE);

		if (DEBUG) {
			log.entering(CNAME, MNAME);
		}

		// Create a new file upload handler
		ServletFileUpload upload = new ServletFileUpload();

		// Parse the request
		FileItemIterator iter = upload.getItemIterator(req);
		while (iter.hasNext()) {
			FileItemStream item = iter.next();
			if (DEBUG) {
				log.fine("Found FileItemStream: " + item);
			}
			handler.handleFileItemStream(item);
		}

		if (DEBUG) {
			log.exiting(CNAME, MNAME);
		}
	}
}
